package com.google.appengine.a4ieve.entities;

import com.google.appengine.a4ieve.Const;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import org.json.JSONObject;

import java.util.Map;
import java.util.Set;

/**
 * User: lunin
 * Date: 4/24/14
 * Time: 9:16 AM
 */
public abstract class EntityWrapper {

    protected Entity entity;

    public abstract JSONObject toJson();

    public EntityWrapper(Entity e){
        this.entity = e;
    }

    protected EntityWrapper(){}

    protected JSONObject toJson(Map<String, ConversionMethod> jsonProperties) {
        JSONObject output = new JSONObject();
        output.put(Const.KEY, KeyFactory.keyToString(entity.getKey()));
        for (Map.Entry<String, ConversionMethod> property : jsonProperties.entrySet()) {
            if (property.getValue() == null) {
                output.put(property.getKey(), entity.getProperty(property.getKey()));
            } else {
                output.put(property.getKey(), property.getValue().convert(entity.getProperty(property.getKey())));
            }
        }
        return output;
    }

    public abstract Map<String, ConversionMethod> getProperties();

    protected interface ConversionMethod {
        Object convert(Object input);
    }
}
